var AldeasInfantiles = angular.module("AldeasInfantiles", ['angularFileUpload']);

AldeasInfantiles.controller("Articles", function($scope, $http, $upload, $timeout) {

  $scope.articles = []; //Array with all registred users in the database
  $scope.hiddenClass = "hidden"; //Used to show or hide the error message in the UI
  $scope.alertClass = ""; //Used to display a message in the UI
  $scope.errorMessage = ""; //Used to change the class of the message div in the UI
  $scope.article = {}; //Donor object
  $scope.articletype = {}; //Donor object
  $scope.selectedtype = ""; //Selected donor country value
  $scope.articlesTypes = [];
  $scope.articlesTypesArray = [];

  //Requests all types
  $scope.requestArticlesTypes = function () {
    $http({
          async: false,
          method: 'POST', 
          url: currentPath + 'articles/returntypes/'
        }).
        success(function(data) {
          $scope.articlesTypes = data;
          $scope.selectedtype = data[0].id_articulotipo;
        }).
        error(function(data, status) {
          console.log(e.message);
        });
  };

  //Requests all types
  $scope.showArticlesTypes = function () {
    $http({
          async: false,
          method: 'POST', 
          url: currentPath + 'articles/returntypes/'
        }).
        success(function(data) {
          $scope.articlesTypesArray = data;
        }).
        error(function(data, status) {
          console.log(e.message);
        });
  };

  //Displays all articles in the UI
  $scope.showArticles = function () {
    $http({
            method: 'POST', 
            url: currentPath + 'articles/returnallarticles/'
        }).
        success(function(data) {
          $scope.articles = data;
        }).
        error(function(data, status) {
           console.log(e.message);
        });
  };

  //Receives the id of an user to get the information from the DB
  $scope.getArticleTypeById = function (article) {
    var id = article.id_articulotipo;
    $http({
            method: 'POST', 
            url: currentPath + 'articles/returnarticletypebyid/' + id
        }).
        success(function(data) {
          $scope.articletype.typeid = data[0].id_articulotipo;
          $scope.articletype.articletypename = data[0].ds_articulotipo;
          $('#modal-articles-types').modal('hide');
        }).
        error(function(data, status) {
           console.log(e.message);
        });
  };


  $scope.getParams = function ($article) {
    $params = $.param({
          'articleid': $article.articleid,
          'articlename': $article.articlename,
          'articletype': $scope.selectedtype,
          'articledescription': $article.description,
          'articlefeatures': $article.features,
          'articlecomments': $article.comments
    })
    $scope.saveArticle($params);
  };

  //Saves the article type in the database
  $scope.saveArticle = function ($article) {

    $http({
        method: 'POST',
        url: currentPath + 'articles/savearticle/',
        secureuri: false,
        headers: {'Content-Type': 'multipart/form-data'},
        dataType: 'json',
        data: {
            articleid: $article.articleid,
            articlename: $article.articlename,
            articletype: $scope.selectedtype,
            articledescription: $article.description,
            articlefeatures: $article.features,
            articlecomments: $article.comments,
        },
        transformRequest: function (data, headersGetter) {
            var formData = new FormData();
            angular.forEach(data, function (value, key) {
                formData.append(key, value);
            });

            var headers = headersGetter();
            delete headers['Content-Type'];

            return formData;
        }
    }).success(function(data, status, headers, config) {
      if(data.response == "success"){
        $scope.errorMessage = "Datos guardatos correctamente";
        $scope.hiddenClass = "";
        $scope.alertClass = "alert-success";
        $scope.resetForm();
      }else if(data.response == "incomplete_form"){
        $scope.hiddenClass = "";
        $scope.alertClass = "alert-danger";
        $scope.errorMessage = "Debes escribir todos los datos del formulario.";
      }else if(data.response == "failed"){
        $scope.hiddenClass = "";
        $scope.alertClass = "alert-danger";
        $scope.errorMessage = "Algo fallo al guardar los datos, intentalo de nuevo.";
      }
    }).error(function (data, status) {
      $scope.hiddenClass = "";
      $scope.errorMessage = data;
    });
  };

  $scope.getParamsType = function ($articletype) {
    $params = $.param({
      'articletypeid': $articletype.typeid,
      'articletypename': $articletype.articletypename
    })
    $scope.saveArticleType($params);
  };

  //Saves the article type in the database
  $scope.saveArticleType = function ($params) {
    $http({
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            url: currentPath + 'articles/savearticletype/',
            method: 'POST',
            data: $params
            
        }).
        success(function(data, status) {
          if(data.response == "success"){
            $scope.errorMessage = "Datos guardatos correctamente";
            $scope.hiddenClass = "";
            $scope.alertClass = "alert-success";
            $scope.resetTypeForm();
            $scope.requestArticlesTypes();
          }else if(data.response == "incomplete_form"){
            $scope.hiddenClass = "";
            $scope.alertClass = "alert-danger";
            $scope.errorMessage = "Debes escribir todos los datos del formulario.";
          }else if(data.response == "failed"){
            $scope.hiddenClass = "";
            $scope.alertClass = "alert-danger";
            $scope.errorMessage = "Algo fallo al guardar los datos, intentalo de nuevo.";
          }
        }).
        error(function(data, status) {
          $scope.hiddenClass = "";
          $scope.errorMessage = data;
        });
  };

  $scope.getArticleById = function(article){
    var id = article.id_articulo;
    $http({
            method: 'POST', 
            url: currentPath + 'articles/returnarticlebyid/' + id
        }).
        success(function(data) {
          $scope.article.articleid = data[0].id_articulo;
          $scope.article.articlename = data[0].ds_articulo;
          $scope.article.description = data[0].ds_descripcion;
          $scope.selectedtype = data[0].id_tipoarticulo;
          $scope.article.features = data[0].ds_caracteristicas;
          $scope.article.comments = data[0].ds_comentarios;
          $('#modal-articles').modal('hide');
        }).
        error(function(data, status) {
           console.log(e.message);
        });
  };
  

  $scope.resetForm = function() {
    $scope.article.articleid = "";
    $scope.article.articlename = "";
    $scope.article.description = "";
    $scope.article.features = "";
    $scope.article.comments = "";
    $timeout(countUp, 5000);
  };

  $scope.resetTypeForm = function() {
    $scope.articletype.typeid = "";
    $scope.articletype.articletypename = "";
    $timeout(countUp, 5000);
  };

  var countUp = function() {
    $scope.hiddenClass = "hidden";
  }

  $scope.setDefaultSettings = function () {
    $scope.requestArticlesTypes();
    $scope.article.articleid = "";
  }

  $scope.setDefaultSettings();

});